//
//  Fraction.m
//  OcDay3homework
//
//  Created by dllo on 16/5/24.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "Fraction.h"

@implementation Fraction
//自定义初始化实现
-(instancetype)initWithMember:(NSInteger)member withDenominator:(NSInteger)denominnator{
    self = [super init];
    if (self) {
        _member = member;
        _denominator = denominnator;
    }
    return self;
}
//便利构造器实现
+(instancetype)FractionWithMember:(NSInteger)member withDenominator:(NSInteger)denominnator{
    Fraction *fra = [[Fraction alloc] initWithMember:member withDenominator:denominnator];
    return fra;
}
//最大公约数
-(NSInteger)maxGCDWithNum1:(NSInteger)num1 withNum2:(NSInteger)num2{
    int newNum1 = abs((int)num1);
    int newNum2 = abs((int)num2);
    while (newNum1 % newNum2) {
        int temp = newNum1 % newNum2;
        newNum1 = newNum2;
        newNum2 = temp;
    }
    return newNum2;
}
//约分
-(void)reduction{
    NSInteger max = [self maxGCDWithNum1:self.member withNum2:self.denominator];
    self.member /= max;
    self.denominator /= max;
    
}
//加法
-(Fraction *)addWithFra:(Fraction *)fra{
    Fraction *fraSum = [[Fraction alloc] init];
    fraSum.member = self.member * fra.denominator + self.denominator * fra.member;
    fraSum.denominator = self.denominator * fra.denominator;
    [fraSum reduction];
    return fraSum;
}
//减法
-(Fraction *)minuWithFra:(Fraction *)fra{
    Fraction *fraMin = [[Fraction alloc] init];
    fraMin.member = self.member * fra.denominator - self.denominator * fra.member;
    fraMin.denominator = self.denominator * fra.denominator;
    [fraMin reduction];
    return fraMin;
}
//乘法
-(Fraction *)multipWithFra:(Fraction *)fra{
    Fraction *fraMul = [[Fraction alloc] init];
    fraMul.member = self.member * fra.member;
    fraMul.denominator = self.denominator * fra.denominator;
    [fraMul reduction];
    return fraMul;
}
//除法
-(Fraction *)divisionWithFra:(Fraction *)fra{
    Fraction *fraDiv = [[Fraction alloc] init];
    Fraction *fraBottom = [[Fraction alloc] init];
    fraBottom.member = fra.denominator;
    fraBottom.denominator = fra.member;
    fraDiv = [self multipWithFra:fraBottom];
    [fraDiv reduction];
    return fraDiv;
}
//比较大小
-(NSComparisonResult)compareWithFra:(Fraction *)fra{
    Fraction *newFra = [self minuWithFra:fra];
    if (newFra.member * newFra.denominator > 0) {
        return NSOrderedDescending; //降序  返回值为1
    } else if (newFra.member * newFra.denominator < 0) {
        return NSOrderedAscending;  //升序  返回值为-1
    } else {
        return NSOrderedSame;  //相等  返回值为0
    }
}
//输出分数
-(void)myPrint{
    NSLog(@"%ld / %ld",self.member,self.denominator);
}











@end
